<template>
  <div class="id-card-query">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>查询条件</span>
          <el-button type="text" @click="resetQuery">重置</el-button>
        </div>
      </template>
      
      <el-form :model="queryForm" label-width="100px" :inline="true">
        <el-form-item label="身份证号">
          <el-input
            v-model="queryForm.personIdCard"
            placeholder="请输入身份证号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        
        <el-form-item label="申请类型">
          <el-select
            v-model="queryForm.applicationType"
            placeholder="请选择申请类型"
            clearable
            style="width: 150px"
          >
            <el-option label="首次申领" value="1" />
            <el-option label="换领" value="2" />
            <el-option label="补领" value="3" />
            <el-option label="注销" value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="申请状态">
          <el-select
            v-model="queryForm.applicationStatus"
            placeholder="请选择申请状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" value="1" />
            <el-option label="审核通过" value="2" />
            <el-option label="审核拒绝" value="3" />
            <el-option label="已完成" value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="申请日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 查询结果 -->
    <el-card class="result-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>查询结果</span>
        </div>
      </template>
      
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="idCard" label="身份证号" width="180" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="applicationDate" label="申请日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.applicationDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="applicationStatus" label="申请状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.applicationStatus)">
              {{ getStatusLabel(row.applicationStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleView(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button 
                v-if="row.applicationStatus === 1" 
                type="success" 
                size="small" 
                @click="handleApprove(row)"
              >
                <el-icon><Check /></el-icon>
                通过
              </el-button>
              <el-button 
                v-if="row.applicationStatus === 1" 
                type="danger" 
                size="small" 
                @click="handleReject(row)"
              >
                <el-icon><Close /></el-icon>
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="申请详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div class="detail-content" v-if="selectedRecord">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="身份证号">{{ selectedRecord.idCard }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ selectedRecord.name }}</el-descriptions-item>
          <el-descriptions-item label="证件类型">{{ getCertificateTypeLabel(selectedRecord.certificateType) }}</el-descriptions-item>
          <el-descriptions-item label="申请类型">{{ getApplicationTypeLabel(selectedRecord.applicationType) }}</el-descriptions-item>
          <el-descriptions-item label="申请原因">{{ selectedRecord.applicationReason }}</el-descriptions-item>
          <el-descriptions-item label="申请日期">{{ formatDate(selectedRecord.applicationDate) }}</el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusTagType(selectedRecord.applicationStatus)">
              {{ getStatusLabel(selectedRecord.applicationStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ selectedRecord.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <el-button @click="handleCloseDetail">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, View, Check, Close } from '@element-plus/icons-vue'
import axios from 'axios'

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8088'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const detailVisible = ref(false)
const selectedRecord = ref(null)

// 查询表单
const queryForm = ref({
  personIdCard: '',
  applicationType: '',
  applicationStatus: '',
  dateRange: []
})

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10
})

// 查询数据
const handleQuery = async () => {
  loading.value = true
  
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('用户未登录，跳过自动查询')
      loading.value = false
      return
    }

    // 构建查询参数 - 只发送必要参数和有值的可选参数
    const params = {
      certificateType: '身份证',  // 必传参数
      pageNum: pagination.value.currentPage,  // 必传参数
      pageSize: pagination.value.pageSize,    // 必传参数
    }

    // 只添加有值的可选参数
    if (queryForm.value.personIdCard && queryForm.value.personIdCard.trim()) {
      params.idCard = queryForm.value.personIdCard.trim()
    }
    if (queryForm.value.applicationType) {
      params.applicationType = parseInt(queryForm.value.applicationType)
    }
    if (queryForm.value.applicationStatus) {
      params.applicationStatus = parseInt(queryForm.value.applicationStatus)
    }

    console.log('发送查询请求，参数:', params)
    console.log('请求地址:', `${API_BASE_URL}/certificate/query`)

    // 调用后端查询接口
    const response = await axios.get(`${API_BASE_URL}/certificate/query`, {
      params,
      headers: { 'token': token }
    })

    console.log('查询响应:', response.data)

    const result = response.data
    if (result.status === 200) {
      tableData.value = result.data || []
      total.value = result.total || 0
      if (tableData.value.length > 0) {
        ElMessage.success('查询成功')
      } else {
        ElMessage.info('暂无数据')
      }
    } else {
      ElMessage.error(result.msg || '查询失败')
      tableData.value = []
      total.value = 0
    }

  } catch (error) {
    console.error('查询出错:', error)
    
    if (error.response) {
      console.error('响应错误:', error.response.status, error.response.data)
      const errorMsg = error.response.data?.msg || `服务器错误 (${error.response.status})`
      ElMessage.error(errorMsg)
    } else if (error.request) {
      console.error('网络请求失败:', error.request)
      ElMessage.error('无法连接到服务器，请检查网络连接或确认后端服务已启动')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error('查询失败: ' + error.message)
    }
    
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryForm.value = {
    personIdCard: '',
    applicationType: '',
    applicationStatus: '',
    dateRange: []
  }
  pagination.value.currentPage = 1
  handleQuery()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  handleQuery()
}

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  handleQuery()
}

// 查看详情
const handleView = (row) => {
  selectedRecord.value = row
  detailVisible.value = true
}

// 关闭详情
const handleCloseDetail = () => {
  detailVisible.value = false
  selectedRecord.value = null
}

// 审批通过
const handleApprove = async (row) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('用户未登录')
      return
    }

    const approvalData = {
      id: row.id,
      applicationStatus: 2  // 2表示审核通过
    }

    console.log('发送审批通过请求，参数:', approvalData)

    const response = await axios.put(`${API_BASE_URL}/certificate/approval`, approvalData, {
      headers: { 'token': token }
    })

    console.log('审批响应:', response.data)

    if (response.data.status === 200) {
      ElMessage.success('审批通过成功')
      // 刷新数据
      handleQuery()
    } else {
      ElMessage.error(response.data.msg || '审批失败')
    }
  } catch (error) {
    console.error('审批出错:', error)
    ElMessage.error('审批失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 审批拒绝
const handleReject = async (row) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('用户未登录')
      return
    }

    const approvalData = {
      id: row.id,
      applicationStatus: 3  // 3表示审核拒绝
    }

    console.log('发送审批拒绝请求，参数:', approvalData)

    const response = await axios.put(`${API_BASE_URL}/certificate/approval`, approvalData, {
      headers: { 'token': token }
    })

    console.log('审批响应:', response.data)

    if (response.data.status === 200) {
      ElMessage.success('审批拒绝成功')
      // 刷新数据
      handleQuery()
    } else {
      ElMessage.error(response.data.msg || '审批失败')
    }
  } catch (error) {
    console.error('审批出错:', error)
    ElMessage.error('审批失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 格式化函数
const getCertificateTypeLabel = (type) => {
  const types = {
    '1': '身份证',
    '2': '临时身份证'
  }
  return types[type] || '未知'
}

const getApplicationTypeLabel = (type) => {
  const types = {
    '1': '首次申领',
    '2': '换领',
    '3': '补领',
    '4': '注销'
  }
  return types[type] || '未知'
}

const getStatusLabel = (status) => {
  const statuses = {
    '1': '待审核',
    '2': '审核通过',
    '3': '审核拒绝',
    '4': '已完成'
  }
  return statuses[status] || '未知'
}

const getStatusTagType = (status) => {
  const types = {
    '1': 'warning',
    '2': 'success',
    '3': 'danger',
    '4': 'info'
  }
  return types[status] || ''
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 页面加载时查询数据
onMounted(() => {
  handleQuery()
})
</script>

<style lang="scss" scoped>
.id-card-query {
  .query-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .result-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-weight: 600;
        color: #303133;
      }
      
      .result-count {
        font-size: 14px;
        color: #909399;
        font-weight: normal;
      }
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .detail-content {
    .el-descriptions {
      margin-top: 20px;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    
    .el-button {
      margin: 0;
      min-width: auto;
      padding: 5px 12px;
    }
  }
}
</style>